const Koa = require("koa");
const app = new Koa();
const views = require("koa-views");
const json = require("koa-json");
const onerror = require("koa-onerror");
const bodyparser = require("koa-bodyparser");
const logger = require("koa-logger");

const index = require("./routes/index");
const users = require("./routes/users");
const menus = require("./routes/menus");
const orgs = require("./routes/orgs");

const cors = require("koa2-cors");
const jwt = require("jsonwebtoken");
const jwtconfig = require("./config/jwtConfig");
const moment = require("moment")

// app.use(
//   cors({
//     origin: () => {
//       return "http://local.kangfx.com:5173";
//     },
//     maxAge: 5, //指定本次预检请求的有效期，单位为秒。
//     credentials: true, //是否允许发送Cookie
//     allowMethods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"], //设置所允许的HTTP请求方法
//     allowHeaders: ["Content-Type", "Authorization", "Accept"], //设置服务器支持的所有头信息字段
//     exposeHeaders: ["WWW-Authenticate", "Server-Authorization"], //设置获取其他自定义字段
//   })
// );
app.use(cors());
const mongoConnect = require("./db");
mongoConnect();
// error handler
onerror(app);

// middlewares
app.use(
  bodyparser({
    enableTypes: ["json", "form", "text"],
  })
);
// 使用koa-body中间件解析FormData格式的请求体
// app.use(koaBody());
app.use(json());
app.use(logger());
app.use(require("koa-static")(__dirname + "/public"));

app.use(
  views(__dirname + "/views", {
    extension: "pug",
  })
);

// logger
app.use(async (ctx, next) => {
  const start = new Date();
  await next();
  const ms = new Date() - start;
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`);
});

// 设置全集jtw的解密中间件
app.use(async (ctx, next) => {
  const userTokne = ctx.header['authorization'];
  // 不检查token
  const whitePaht = [
    '/users/login'
  ]
  if (whitePaht.includes(ctx.url)) {
    await next();
  } else {
    await jwt.verify(userTokne, jwtconfig.Key, async (err, data) => {
      if (err) {
        ctx.body = {
          code: 401, msg: "身份验证失败"
        }
        return;
      }
      if (Number(moment().format('X')) > data.exp) {
        ctx.body = {
          code: 401, msg: "登录过期"
        }
        return;
      } else {
        await next()
      }
    });
  }
});

// routes
app.use(index.routes(), index.allowedMethods());
app.use(users.routes(), users.allowedMethods());
app.use(menus.routes(), menus.allowedMethods());
app.use(orgs.routes(), orgs.allowedMethods());

// error-handling
app.on("error", (err, ctx) => {
  console.error("server error", err, ctx);
});

module.exports = app;
